﻿
using System;
using System.Collections.ObjectModel;
using System.IO;
using log4net;
using WPFEdit.Document;
using WPFEdit.Framework;
using WPFEdit.Util;
using WPFEdit.ViewModels;
using WPFEdit.Views;
using MenuItem = WPFEdit.ViewModels.MenuItem;

namespace SampleApp
{
    class SampleDocumentManager : DocumentManager
    {

        MainMenuModel m_mainMenu = new MainMenuModel();

        private MenuItem m_saveMenuItem;

        private static ILog s_logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public override void AddInitSteps(Task task)
        {

            task.AddStep(new TaskStep()
            {
                StatusText = "Initialzing UI",
                UIThreadPreWork = () =>
                {
                    ObservableCollection<MenuItem> fileMenu = m_mainMenu.FileMenu.SubMenu;

                    fileMenu.Add(new MenuItem() { Name = "Open...", Command = new NoArgDelegateCommand(this.OpenFileDialog) });
                    m_saveMenuItem = new MenuItem() { Name = "Save", Enabled = false, Command = new NoArgDelegateCommand(this.SaveSelectedDocument) };

                    fileMenu.Add(m_saveMenuItem);

					this.ErrorHandler = new ErrorHandler();
                },
                StepAction = () =>
                {
                    AddFactoryAssembly(this.GetType().Assembly);
                    this.SelectedDocumentChanged += SampleOnSelectedDocumentChanged;
                }
            });

            base.AddInitSteps(task);
        }

		void SampleHandleError(string message, Exception ex)
		{
			ErrorHandler.HandlerError(message, ex, s_logger);
		}

        void SampleOnSelectedDocumentChanged(object sender, DocumentEventArgs e)
        {
            if (SelectedDocument != null) SelectedDocument.PropertyChanged -= SelectedDocumentPropertyChanged;

            if (e.DocumentInfo != null)
            {
                e.DocumentInfo.PropertyChanged += SelectedDocumentPropertyChanged;
                m_saveMenuItem.Enabled = e.DocumentInfo.HasUnsavedChanges;
            }
            else
            {
                m_saveMenuItem.Enabled = false;
            }
        }

        void SelectedDocumentPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "HasUnsavedChanges")
            {
                m_saveMenuItem.Enabled = SelectedDocument.HasUnsavedChanges;
            }
        }


        internal MainMenuModel MainMenu
        {
            get { return m_mainMenu; }
            set { m_mainMenu = value; }
        }

        internal bool SaveEnabled
        {
            get { return m_saveMenuItem.Enabled; }
            set { m_saveMenuItem.Enabled = value; }
        }
    }
}